// pages/orderDetail/orderDetail.js
Page({
    data: {
        orderId: '', // 订单ID
        orderInfo: {}, // 订单信息
        isLoading: true, // 加载状态
        statusTitles: [ // 状态对应的导航标题
            '待付款',
            '待发货',
            '待收货',
            '已完成'
        ],
        addressInfo: {}, // 收货地址信息
        goodsInfo: {}, // 商品信息
        userInfo: {}, // 当前用户信息
        showShipBtn: false, // 显示发货按钮
        showReceiveBtn: false, // 显示收货按钮
        showShipModal: false, // 发货表单弹窗显示状态
        shipMethod: '', // 选择的发货方式
        expressCompany: '', // 快递公司
        expressNumber: '', // 快递单号
        currentOrderId: '' // 当前处理的订单ID
    },

    onLoad(options) {
        const orderId = options.orderId;
        if (!orderId) {
            wx.showToast({
                title: '订单ID缺失',
                icon: 'none'
            });
            setTimeout(() => {
                wx.navigateBack();
            }, 1500);
            return;
        }

        this.setData({
            orderId: orderId
        });

        // 获取用户信息
        this.getUserInfo();

        // 获取订单详情
        this.getOrderDetail(orderId);
    },

    // 获取用户信息
    getUserInfo() {
        const userInfo = wx.getStorageSync('userInfo');
        if (userInfo) {
            this.setData({
                userInfo: userInfo
            });
        } else {
            wx.showToast({
                title: '请先登录',
                icon: 'none'
            });
            setTimeout(() => {
                wx.navigateTo({
                    url: '/pages/login/login'
                });
            }, 1500);
        }
    },

    // 获取订单详情
    async getOrderDetail(orderId) {
        try {
            this.setData({
                isLoading: true
            });

            // 调用云函数获取订单详情
            const res = await wx.cloud.callFunction({
                name: 'getOrderDetail',
                data: {
                    orderId: orderId
                }
            });
            console.log(res);
            if (res.result.success) {
                const orderInfo = res.result.orderInfo;
                const status = orderInfo.status;
                if (orderInfo.goodsInfo.goodsImage) {
                    let arr = orderInfo.goodsInfo.goodsImage.split(',')
                    orderInfo.goodsInfo.Image = arr
                }
                // 设置导航栏标题
                wx.setNavigationBarTitle({
                    title: this.data.statusTitles[status - 1] || '订单详情'
                });
                //发货方式
                if (orderInfo.shipInfo) {
                    orderInfo.shipInfo.shipMethodText = this.getShipMethodText(orderInfo.shipInfo.method)
                }
                // 格式化时间
                const formattedOrder = this.formatOrderTime(orderInfo);


                // 判断是否显示操作按钮
                const showShipBtn =
                    this.data.userInfo._id === orderInfo.sellerId &&
                    status === 2; // 卖家且待发货状态

                const showReceiveBtn =
                    this.data.userInfo._id === orderInfo.buyerId &&
                    status === 3; // 买家且待收货状态

                this.setData({
                    orderInfo: formattedOrder,
                    addressInfo: orderInfo.addressInfo || {},
                    goodsInfo: orderInfo.goodsInfo || {},
                    showShipBtn: showShipBtn,
                    showReceiveBtn: showReceiveBtn,
                    isLoading: false
                });
            } else {
                wx.showToast({
                    title: res.result.message || '获取订单详情失败',
                    icon: 'none'
                });
                setTimeout(() => {
                    wx.navigateBack();
                }, 1500);
            }
        } catch (error) {
            console.error('获取订单详情失败:', error);
            wx.showToast({
                title: '系统错误，请重试',
                icon: 'none'
            });
            this.setData({
                isLoading: false
            });
        }
    },
    // 获取发货方式文本
    getShipMethodText: function (method) {
        const methodMap = {
            'express': '物流快递',
            'selfPickup': '用户自提',
            'localDelivery': '同城配送'
        };
        return methodMap[method] || method;
    },
    // 格式化订单时间
    formatOrderTime(order) {
        const formatted = {
            ...order
        };
        const timeFields = ['createTime', 'payTime', 'shipTime', 'receiveTime'];

        timeFields.forEach(field => {
            if (formatted[field]) {
                formatted[field] = this.formatTime(formatted[field]);
            } else {
                formatted[field] = '未记录';
            }
        });

        return formatted;
    },

    // 格式化时间戳为友好格式
    formatTime(timestamp) {
        if (!timestamp) return '未记录';

        const date = new Date(timestamp);
        return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    },


    // 发货操作
    handleShipOrder() {
        const {
            orderId,
            orderInfo
        } = this.data;
        this.setData({
            showShipModal: true,
            currentOrderId: orderId,
            shipMethod: '',
            expressCompany: '',
            expressNumber: ''
        });
        // wx.showModal({
        //     title: '确认发货',
        //     content: '是否确认已发货？',
        //     success: (res) => {
        //         if (res.confirm) {
        //             this.updateOrderStatus(orderId, 3); // 更新为已发货状态
        //         }
        //     }
        // });
    },
    // 选择发货方式
    selectShipMethod: function (e) {
        const method = e.currentTarget.dataset.method;
        this.setData({
            shipMethod: method
        });
    },

    // 快递公司输入
    onExpressCompanyInput: function (e) {
        this.setData({
            expressCompany: e.detail.value
        });
    },

    // 快递单号输入
    onExpressNumberInput: function (e) {
        this.setData({
            expressNumber: e.detail.value
        });
    },

    // 关闭发货表单
    closeShipModal: function () {
        this.setData({
            showShipModal: false
        });
    },

    // 确认发货
    confirmShipOrder: function () {
        const {
            currentOrderId,
            shipMethod,
            expressCompany,
            expressNumber
        } = this.data;

        // 验证输入
        if (!shipMethod) {
            wx.showToast({
                title: '请选择发货方式',
                icon: 'none'
            });
            return;
        }

        if (shipMethod === 'express' && (!expressCompany || !expressNumber)) {
            wx.showToast({
                title: '请填写快递公司和快递单号',
                icon: 'none'
            });
            return;
        }

        // 显示加载状态
        wx.showLoading({
            title: '发货中...',
        });
        // 调用云函数
        wx.cloud.callFunction({
            name: 'shipOrder',
            data: {
                orderId: currentOrderId,
                shipMethod: shipMethod,
                expressCompany: expressCompany,
                expressNumber: expressNumber,
                operatorId: wx.getStorageSync('userInfo')._id,
                operatorName: wx.getStorageSync('userInfo').nickName
            }
        }).then(res => {
            wx.hideLoading();

            if (res.result.success) {
                wx.showToast({
                    title: '发货成功',
                    icon: 'success'
                });
                this.closeShipModal();
                // 刷新订单列表
                this.loadOrderList(this.data.currentTab);
            } else {
                wx.showToast({
                    title: res.result.message || '发货失败',
                    icon: 'none'
                });
                console.error('发货失败', res.result.error);
            }
        }).catch(err => {
            wx.hideLoading();
            wx.showToast({
                title: '网络错误，请重试',
                icon: 'none'
            });
            console.error('调用云函数失败', err);
        });
    },
    // 确认收货操作
    handleReceiveOrder() {
        const {
            orderId,
            orderInfo
        } = this.data;
        wx.showModal({
            title: '确认收货',
            content: '是否确认已收到商品？',
            success: (res) => {
                if (res.confirm) {
                    this.updateOrderStatus(orderId, 4); // 更新为已完成状态
                }
            }
        });
    },

    // 更新订单状态
    async updateOrderStatus(orderId, newStatus) {
        try {
            wx.showLoading({
                title: '处理中...'
            });

            // 调用云函数更新订单状态
            const res = await wx.cloud.callFunction({
                name: 'updateOrderStatus',
                data: {
                    orderId: orderId,
                    newStatus: newStatus
                }
            });

            wx.hideLoading();

            if (res.result.success) {
                wx.showToast({
                    title: '操作成功',
                    icon: 'success'
                });

                // 刷新订单详情
                this.getOrderDetail(orderId);
            } else {
                wx.showToast({
                    title: res.result.message || '操作失败',
                    icon: 'none'
                });
            }
        } catch (error) {
            wx.hideLoading();
            console.error('更新订单状态失败:', error);
            wx.showToast({
                title: '系统错误，请重试',
                icon: 'none'
            });
        }
    },
    handleGoodsDetais(e) {
        console.log(e);
        const goodsId = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: `/pages/goods/index?goodsId=${goodsId}`
        });
    }
});